/**
 * Created by lihao on 2017/11/13
 *  用nodejs连接数据库 和相应的数据请求
 */

let express = require('express');
let router =  express.Router();
let mysql  =  require('mysql');
let fs = require('fs');
let path = require('path');
let con = mysql.createConnection({
    host:'localhost',
    port:'3306',
    user:'root',
    password:'p081742linuxZH#',
    database:'new_schema',
    dateStrings: true
});

con.connect();   //连接数据库

router.get('/',function(req,res,next){
    let sql_url = req.query.url;

    //判断给出的路径是否存在
    let url_path = path.resolve('./sql/'+sql_url+'.js');
    fs.exists(url_path,function(flag){
        console.log('URL:'+url_path+'; exists:',flag);
        if(flag){
            let res_data = require('../sql/'+sql_url);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end( JSON.stringify(res_data));

        //    没有相应接口时
        }  else {
            // res.render('404error',{message:'Not Found 404'})     //页面
            let error_temp ={
                success: false,
                data:"",
                error:'404 Not Found',
            };

            res.end(JSON.stringify(error_temp))
        }
    });


});

module.exports = router;
